package cn.nzcong.jpress.addon.articlesync.service.impl;

import cn.nzcong.jpress.addon.articlesync.annotation.SecondStep;
import cn.nzcong.jpress.addon.articlesync.common.Constant;
import cn.nzcong.jpress.addon.articlesync.common.Exception.InternalServiceException;
import cn.nzcong.jpress.addon.articlesync.service.ConfigService;
import cn.nzcong.jpress.addon.articlesync.vo.ConfigFactory;
import cn.nzcong.jpress.addon.articlesync.vo.config.BaseConfig;
import cn.nzcong.jpress.addon.articlesync.vo.config.SecondStepConfig;
import com.jfinal.aop.Inject;
import io.jboot.aop.annotation.Bean;
import io.jpress.service.OptionService;

/**
 * 基于JPress的option表进行配置管理
 */
@Bean
public class ConfigOptionService implements ConfigService {

    @Inject
    OptionService optionService;


    @Override
    public void saveSecondStepConfig(SecondStepConfig jsonObject) {
        optionService.saveOrUpdate(Constant.OPTION_SSA_CONFIG_KEY, jsonObject.toEncryptString());
    }

    @Override
    public SecondStepConfig getSecondStepConfig() {
        SecondStepConfig config = ConfigFactory.getByString(optionService.findByKey(Constant.OPTION_SSA_CONFIG_KEY), SecondStepConfig.class);
        return config == null ? new SecondStepConfig() : config;
    }

    @Override
    public void deleteSecondStepConfig() {
        optionService.deleteByKey(Constant.OPTION_SSA_CONFIG_KEY);
    }

    @Override
    public void savePlatformConfig(String platformName, BaseConfig jsonObject) {
        optionService.saveOrUpdate(Constant.OPTION_ACCOUNT_PREFIX(platformName), jsonObject.toEncryptString());
    }

    @Override
    public <T extends BaseConfig> T getPlatformConfig(String platformName, Class<T> clazz) {
        try {
            BaseConfig config = ConfigFactory.getByString(optionService.findByKey(Constant.OPTION_ACCOUNT_PREFIX(platformName)), clazz);
            return clazz.cast(config);
        } catch (Exception e) {
            throw new InternalServiceException(e, "配置转换失败");
        }
    }

    @Override
    public void deletePlatformConfig(String platformName) {
        optionService.deleteByKey(Constant.OPTION_ACCOUNT_PREFIX(platformName));
    }
}
